package cn.iocoder.yudao.module.member.service.email;

import cn.iocoder.yudao.module.member.controller.app.email.vo.AppEmailSaveReqVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import cn.iocoder.yudao.module.member.controller.admin.email.vo.*;
import cn.iocoder.yudao.module.member.dal.dataobject.email.EmailDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.member.dal.mysql.email.EmailMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;

/**
 * 用户邮箱 Service 实现类
 *
 * @author 超管
 */
@Service
@Validated
public class EmailServiceImpl implements EmailService {

    @Resource
    private EmailMapper emailMapper;

    @Override
    public Long createEmail(EmailSaveReqVO createReqVO) {
        // 插入
        EmailDO email = BeanUtils.toBean(createReqVO, EmailDO.class);
        emailMapper.insert(email);
        // 返回
        return email.getId();
    }

    @Override
    public void updateEmail(EmailSaveReqVO updateReqVO) {
        // 校验存在
        validateEmailExists(updateReqVO.getId());
        // 更新
        EmailDO updateObj = BeanUtils.toBean(updateReqVO, EmailDO.class);
        emailMapper.updateById(updateObj);
    }

    @Override
    public void deleteEmail(Long id) {
        // 校验存在
        validateEmailExists(id);
        // 删除
        emailMapper.deleteById(id);
    }

    private void validateEmailExists(Long id) {
        if (emailMapper.selectById(id) == null) {
            throw exception(EMAIL_NOT_EXISTS);
        }
    }

    @Override
    public EmailDO getEmail(Long id) {
        return emailMapper.selectById(id);
    }

    @Override
    public PageResult<EmailDO> getEmailPage(EmailPageReqVO pageReqVO) {
        return emailMapper.selectPage(pageReqVO);
    }

    @Override
    public Long createEmailByUser(Long userId, AppEmailSaveReqVO createReqVO) {
        final EmailDO emailDO = emailMapper.getByEmail(userId, createReqVO.getEmail());
        if (emailDO != null) {
            // 更新
            emailMapper.updateUsageCount(emailDO.getId());
            return emailDO.getId();
        } else {
            // 插入
            final EmailDO email = BeanUtils.toBean(createReqVO, EmailDO.class);
            email.setUserId(userId);
            emailMapper.insert(email);
            // 返回
            return email.getId();
        }
    }

    @Override
    public List<EmailDO> getEmailOrderByUpdateTime(Long userId, int limitSize) {
        return emailMapper.getEmailOrderByUpdateTime(userId, limitSize);
    }
}